import base64
import json
import rsa
import sqlite3
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
import backend.DID.BlockChain as BlockChain
import backend.DID.Identity_Management as Identity_Management
import backend.DID.En_Decrypt_Management as En_Decrypt_Management
import backend.DID.DataBase as DataBase
import backend.DID.Communication_Management as Communication_Management
from backend.DID.Certification_Management import Certify
import backend.P2P.auth as auth
from backend.DID.Identity_Management import CreateIdentity1


conn = sqlite3.connect("p2p.db")
cursor = conn.cursor()

def CreateIdentity(cpu_id, disk_id, product_id, username, password):
    try:
        return CreateIdentity1(product_id, cpu_id, disk_id, username, password)
    except Exception as e:
        print(f"DID部分创建身份出错，错误为{e}")


# 2. 身份认证
def verify(cpu_id, disk_id, product_id, username, password,user_did):
    try:
        return Certify(product_id, cpu_id, disk_id, username, password,user_did)
    except Exception as e:
        print(f"DID部分身份认证出错，错误为{e}")


# 3. 加密函数      # 存储数据到数据库时调用,传入为json
def encrypt(cpu_id, disk_id, product_id, data):
    try:
        hard_disk_number =(
            product_id,
            cpu_id,
            disk_id
        )
        hash = Identity_Management.hashFunction(hard_disk_number)
        hash1 = {
            'hash1': hash
        }
        table = 'blockchain'
        search_data='publickey'
        publickey_bytes = BlockChain.query_data(table, hash1, search_data).encode('utf-8')
        publickey=rsa.PublicKey.load_pkcs1(publickey_bytes)

        # 使用分块加密
        data_bytes = json.dumps(data).encode('utf-8')
        encrypted_data = En_Decrypt_Management.encrypt_by_publickey(data_bytes, publickey)

        # encrypt_data=En_Decrypt_Management.encrypt_by_publickey(json.dumps(data).encode('utf-8'),publickey)
        return encrypted_data
        # 使用分块加密
        data_bytes = json.dumps(data).encode('utf-8')
        encrypted_data = En_Decrypt_Management.encrypt_by_publickey(data_bytes, publickey)

        # encrypt_data=En_Decrypt_Management.encrypt_by_publickey(json.dumps(data).encode('utf-8'),publickey)
        return encrypted_data
    except Exception as e:
        print(f"DID到p2p加密失败: {e}")
        return 0


# 4. 解密函数（已测试）    # 从数据库中取出时调用
def decrypt(cpu_id, disk_id, product_id, data):
    try:
        hard_disk_number = (
            product_id,
            cpu_id,
            disk_id
        )
        hash = Identity_Management.hashFunction(hard_disk_number)
        the_path='user.db'
        the_path='user.db'
        table = 'user'
        password=DataBase.search_data(the_path,table,'hash1',hash,'password')
        private_key=DataBase.search_data(the_path,table,'hash1',hash,'private_key')

        private_key_decrypt=En_Decrypt_Management.decrypt_privatekey(private_key,password).encode('utf-8')
        privatekey=rsa.PrivateKey.load_pkcs1(private_key_decrypt)

        # 使用分块解密
        decrypted_data = En_Decrypt_Management.decrypt_by_privatekey(data, privatekey)
        if not decrypted_data:
            return 0

        # decrypt_data=En_Decrypt_Management.decrypt_by_privatekey(data,privatekey)
        return json.loads(decrypted_data.decode('utf-8'))
        # 使用分块解密
        decrypted_data = En_Decrypt_Management.decrypt_by_privatekey(data, privatekey)
        if not decrypted_data:
            return 0

        # decrypt_data=En_Decrypt_Management.decrypt_by_privatekey(data,privatekey)
        return json.loads(decrypted_data.decode('utf-8'))
    except Exception as e:
        print(f"DID到p2p解密失败: {e}")
        return 0

# 5. 加密通道（已测试）  receiver_did: 对方的DID,port: 目标端口号,sender_did: 自己的DID标识 ip:对方IP（服务端）
def DID_connect(receiver_did,port,sender_did,ip):
    try:
        return Communication_Management.DID_connect(receiver_did,port,sender_did,ip)
    except Exception as e:
        print(f"DID到p2p DID_connect失败:{e}")
        return 0
def DID_listen(sender_did,port):    # sender_did: 自己的DID标识,port: 监听的端口号
    try:
        return Communication_Management.DID_listen(sender_did,port)
    except Exception as e:
        print(f"DID到p2p DID_listen失败:{e}")
        return 0
def DID_send(data):   # data：需要发送的信息
    try:
        return Communication_Management.DID_send(json.dumps(data).encode('utf-8'))
    except:
        print(f"DID到p2p DID_send失败")
        return 0
def DID_recv():
    try:
        return json.loads(Communication_Management.DID_recv().decode('utf-8'))
    except:
        print(f"DID到p2p DID_recv失败")
        return 0
def DID_close():
    try:
        return Communication_Management.DID_close()
    except:
        print(f"DID到p2p DID_close失败")
        return 0
def DID_accept():
    try:
        return Communication_Management.DID_accept()
    except:
        print(f"DID到p2p DID_accept失败")
        return 0

#6.信息同步

# 跨机向本机请求信息同步
# 请求信息同步(跨机)  跨机底层did，本机底层did， 目标ip
def meg_sync_require(sender_did,receiver_did,ip,request):
    try:
        port=8888

        if DID_connect(receiver_did,port,sender_did,ip):
            DID_send(request)
            print("请求信息已发送")

        receive_data=DID_recv()

        data = {k: base64.b64decode(v)
                for k, v in receive_data.items()}
        decrypt_data = En_Decrypt_Management.decrypt_package(data)

        # print(f"decrypt_data:{decrypt_data}")
        print(f"收到同步信息")
        response = "已收到同步信息"
        if DID_send(response):
            print("响应发送成功")
        DID_close()
        return decrypt_data
    except Exception as e:
        print(f"DID到p2p meg_sync_require失败:{e}")
        DID_close()
        return 0

#    ------------------------部分函数-------------------------------

# 本机查询给跨机的数据
def get_info(modules, owner_did):
    response = {}
    basic_info = {}

    if "friends" in modules:
        basic_info["friends"] = get_all_friends(owner_did)  # 从数据库获取好友信息

    if "groups" in modules:
        basic_info["groups"] = get_all_groups(owner_did)  # 从数据库获取群聊信息

    if basic_info:
        response["basic_info"] = basic_info  # 将 key 为 "basic_info" 的一整块数据加入 response 中

    # 聊天记录
    if "messages" in modules:
        response["messages"] = get_all_messages(owner_did)  # 从数据库获取聊天记录

    return response


# 本机从数据库读好友基础信息，加载好友信息时也可调用
def get_all_friends(owner):
    cursor.execute("SELECT id, name, ip, online,owner FROM friends where owner=?", (owner,))

    rows = cursor.fetchall()  # 取出所有的好友信息

    # 构建成列表字典格式
    friends = []
    for row in rows:
        friend = {
            "id": row[0],
            "name": row[1],
            "ip": row[2],
            "online": bool(row[3]),  # 转换成 True/False
            "owner": row[4]
        }
        friends.append(friend)

    conn.close()
    return friends


# 本机从数据库读群聊基础信息，加载群聊信息时也可调用
def get_all_groups(owner):
    cursor.execute("SELECT groupId, groupname,members,timestamp,owner from tblGroup where owner = ?",
                   (owner,))  # members这个字段包括了群成员的基本信息，以及在线状态

    rows = cursor.fetchall()  # 取出所有的群成员（包括群主）信息

    # 构建成列表字典格式（便于 JSON 序列化）
    groups = []
    for row in rows:
        group = {
            "groupId": row[0],
            "groupname": row[1],
            "members": row[2],
            "timestamp": row[3],
            "owner": row[4]
        }
        groups.append(group)

    conn.close()
    return groups



# 本机从数据库读取单人和群聊聊天记录
def get_all_messages(owner):
    with sqlite3.connect("p2p.db", check_same_thread=False) as conn:
        cursor = conn.cursor()
    # 获取设备信息
    cpu_id, disk_id, product_id = auth.get_device_info()

    # 获取单聊记录
    cursor.execute("SELECT id, friend_id, sent,message, timestamp ,is_sent ,owner FROM messages where owner = ?",
                   (owner,))
    private_rows = cursor.fetchall()
    private_msgs = []
    for row in private_rows:
        message = decrypt(cpu_id, disk_id, product_id, row["message"])  # 解密这条消息
        private_msgs.append({
            "id": row[0],
            "friend_id": row[1],
            "sent": row[2],
            "message": message,
            "timestamp": row[4],
            "is_sent": row[5],
            "owner": owner
        })

    # 获取群聊记录
    cursor.execute(
        "SELECT sender,receiver, message, timestamp,msg_type, groupId,owner FROM group_message where owner = ?",
        (owner,))
    group_rows = cursor.fetchall()
    group_msgs = []
    for group_row in group_rows:
        group_message = decrypt(cpu_id, disk_id, product_id, group_row["message"])  # 解密这条消息
        group_msgs.append({
            "sender": group_row[0],
            "receiver": group_row[1],
            "message": group_message,
            "timestamp": group_row[3],
            "msg_type": group_row[4],
            "groupId": group_row[5],
            "owner": owner
        })

    conn.close()
    # 打包成统一结构
    messages = {
        "private": private_msgs,
        "group": group_msgs
    }

    return messages


#    ------------------------部分函数-------------------------------

# 信息同步（本机）   sender_did:本机底层DID
def meg_sync(sender_did):
    try:
        listen_port = 8888
        if DID_listen(sender_did,listen_port):
            print("等待接收数据...")
        request=DID_recv()


        receiver_did=request.get("kuaji_did")
        if request.get("action")=="SYNC_REQUEST":
            modules=request.get("moudules",[])
            data=get_info(modules,sender_did)        # 导入


            # print(meg)
            encrypt_data = En_Decrypt_Management.encrypt_package(sender_did, receiver_did, json.dumps(data).encode('utf-8'))
            # print(f"encrypt:{encrypt_data}")
            serializable = {k: base64.b64encode(v).decode('ascii') for k, v in encrypt_data.items()}


            # print(f"ddd:{payload}")
            print("准备发送加密包")

            if DID_send(serializable):
                print("数据发送成功")
            response = DID_recv()
            print(f"收到响应：{response}")
            DID_close()
            return True

    except Exception as e:
        print(f"DID到p2p meg_sync失败:{e}")
        return 0








# 本机接收并同步跨机的信息
# 跨机   sender_did: 跨机底层did    receiver_did:本机底层did
def meg_sync_send(sender_did,receiver_did,data,ip):
    try:
        port=8888
        encrypt_data=En_Decrypt_Management.encrypt_package(sender_did,receiver_did,json.dumps(data).encode('utf-8'))
        # print(f"encrypt:{encrypt_data}")
        serializable = {k: base64.b64encode(v).decode('ascii') for k, v in encrypt_data.items()}

        payload = json.dumps(serializable).encode('utf-8')
        if Communication_Management.DID_connect(receiver_did,port,sender_did,ip):
            print("准备发送加密包")
            # print(f"ddd:{payload}")
        if Communication_Management.DID_send(payload):
            print("数据发送成功")
        response=Communication_Management.DID_recv()
        print(f"收到响应：{response.decode('utf-8')}")
        Communication_Management.DID_close()
        return 1
    except Exception as e:
        print(f"DID到p2p meg_sync_send失败:{e}")
        Communication_Management.DID_close()
        return 0

# 本机   receiver_did: 本机底层did
def meg_sync_receive(receiver_did):
    try:
        listen_port=8888
        if Communication_Management.DID_listen(receiver_did,listen_port):
            print("等待接收数据...")
        receive_data=json.loads(Communication_Management.DID_recv().decode('utf-8'))

        data = {k: base64.b64decode(v)  #  base64 字符串 -> 原始 bytes
                        for k, v in receive_data.items()}
        decrypt_data=En_Decrypt_Management.decrypt_package(data)


        print(f"收到同步信息")
        response="已收到同步信息"
        if Communication_Management.DID_send(response):
            print("响应发送成功")
        Communication_Management.DID_close()
        return decrypt_data
    except Exception as e:
        print(f"DID到p2p meg_sync_receive失败:{e}")
        Communication_Management.DID_close()
        return 0

#7.创建群聊（准备密码包）(已测试)
def create_and_share_groupkey(groupID,member_id):
    try:                                   # 为方便遍历，群成员id(即DID)请用数组(即列表)打包，其中第一个元素为群主DID
        En_Decrypt_Management.create_group(groupID,member_id)
        print("密钥上传成功！")
    except:
        print(f"DID到p2p创建群聊失败")
        return 0

#8.群消息加密（已测试）
def group_meg_encrypt(groupID,did,data):
    try:
        group_key=En_Decrypt_Management.get_groupkey(groupID,did)
        encrypt_meg=En_Decrypt_Management.encrypt_by_sharekey(group_key,json.dumps(data).encode('utf-8'))
        return encrypt_meg        # 返回加密后的信息
    except:
        print(f"DID到p2p群消息加密失败")
        return 0

#9.群消息解密（已测试）
def group_meg_decrypt(groupID,did,encrypt_data):
    try:
        group_key=En_Decrypt_Management.get_groupkey(groupID,did)
        decrypt_meg=En_Decrypt_Management.decrypt_by_sharekey(group_key,encrypt_data)
        return json.loads(decrypt_meg.decode('utf-8'))   # 返回解密后的信息
    except:
        print(f"DID到p2p群消息解密失败")
        return 0



# 本机从数据库读群聊基础信息，加载群聊信息时也可调用
def get_all_groups(owner):
    cursor.execute("SELECT groupId, groupname,members,timestamp,owner from tblGroup where owner = ?",
                   (owner,))  # members这个字段包括了群成员的基本信息，以及在线状态

    rows = cursor.fetchall()  # 取出所有的群成员（包括群主）信息

    # 构建成列表字典格式（便于 JSON 序列化）
    groups = []
    for row in rows:
        group = {
            "groupId": row[0],
            "groupname": row[1],
            "members": row[2],
            "timestamp": row[3],
            "owner": row[4]
        }
        groups.append(group)

    conn.close()
    return groups



# 本机从数据库读取单人和群聊聊天记录
def get_all_messages(owner):
    with sqlite3.connect("p2p.db", check_same_thread=False) as conn:
        cursor = conn.cursor()
    # 获取设备信息
    cpu_id, disk_id, product_id = auth.get_device_info()

    # 获取单聊记录
    cursor.execute("SELECT id, friend_id, sent,message, timestamp ,is_sent ,owner FROM messages where owner = ?",
                   (owner,))
    private_rows = cursor.fetchall()
    private_msgs = []
    for row in private_rows:
        message = decrypt(cpu_id, disk_id, product_id, row["message"])  # 解密这条消息
        private_msgs.append({
            "id": row[0],
            "friend_id": row[1],
            "sent": row[2],
            "message": message,
            "timestamp": row[4],
            "is_sent": row[5],
            "owner": owner
        })

    # 获取群聊记录
    cursor.execute(
        "SELECT sender,receiver, message, timestamp,msg_type, groupId,owner FROM group_message where owner = ?",
        (owner,))
    group_rows = cursor.fetchall()
    group_msgs = []
    for group_row in group_rows:
        group_message = decrypt(cpu_id, disk_id, product_id, group_row["message"])  # 解密这条消息
        group_msgs.append({
            "sender": group_row[0],
            "receiver": group_row[1],
            "message": group_message,
            "timestamp": group_row[3],
            "msg_type": group_row[4],
            "groupId": group_row[5],
            "owner": owner
        })

    conn.close()
    # 打包成统一结构
    messages = {
        "private": private_msgs,
        "group": group_msgs
    }

    return messages


#    ------------------------部分函数-------------------------------

# 信息同步（本机）   sender_did:本机底层DID
def meg_sync(sender_did):
    try:
        listen_port = 8888
        if DID_listen(sender_did,listen_port):
            print("等待接收数据...")
        request=DID_recv()


        receiver_did=request.get("kuaji_did")
        if request.get("action")=="SYNC_REQUEST":
            modules=request.get("moudules",[])
            data=get_info(modules,sender_did)        # 导入


            # print(meg)
            encrypt_data = En_Decrypt_Management.encrypt_package(sender_did, receiver_did, json.dumps(data).encode('utf-8'))
            # print(f"encrypt:{encrypt_data}")
            serializable = {k: base64.b64encode(v).decode('ascii') for k, v in encrypt_data.items()}


            # print(f"ddd:{payload}")
            print("准备发送加密包")

            if DID_send(serializable):
                print("数据发送成功")
            response = DID_recv()
            print(f"收到响应：{response}")
            DID_close()
            return True

    except Exception as e:
        print(f"DID到p2p meg_sync失败:{e}")
        return 0








# 本机接收并同步跨机的信息
# 跨机   sender_did: 跨机底层did    receiver_did:本机底层did
def meg_sync_send(sender_did,receiver_did,data,ip):
    try:
        port=8888
        encrypt_data=En_Decrypt_Management.encrypt_package(sender_did,receiver_did,json.dumps(data).encode('utf-8'))
        # print(f"encrypt:{encrypt_data}")
        serializable = {k: base64.b64encode(v).decode('ascii') for k, v in encrypt_data.items()}

        payload = json.dumps(serializable).encode('utf-8')
        if Communication_Management.DID_connect(receiver_did,port,sender_did,ip):
            print("准备发送加密包")
            # print(f"ddd:{payload}")
        if Communication_Management.DID_send(payload):
            print("数据发送成功")
        response=Communication_Management.DID_recv()
        print(f"收到响应：{response.decode('utf-8')}")
        Communication_Management.DID_close()
        return 1
    except Exception as e:
        print(f"DID到p2p meg_sync_send失败:{e}")
        Communication_Management.DID_close()
        return 0

# 本机   receiver_did: 本机底层did
def meg_sync_receive(receiver_did):
    try:
        listen_port=8888
        if Communication_Management.DID_listen(receiver_did,listen_port):
            print("等待接收数据...")
        receive_data=json.loads(Communication_Management.DID_recv().decode('utf-8'))

        data = {k: base64.b64decode(v)  #  base64 字符串 -> 原始 bytes
                        for k, v in receive_data.items()}
        decrypt_data=En_Decrypt_Management.decrypt_package(data)


        print(f"收到同步信息")
        response="已收到同步信息"
        if Communication_Management.DID_send(response):
            print("响应发送成功")
        Communication_Management.DID_close()
        return decrypt_data
    except Exception as e:
        print(f"DID到p2p meg_sync_receive失败:{e}")
        Communication_Management.DID_close()
        return 0

#7.创建群聊（准备密码包）(已测试)
def create_and_share_groupkey(groupID,member_id):
    try:                                   # 为方便遍历，群成员id(即DID)请用数组(即列表)打包，其中第一个元素为群主DID
        En_Decrypt_Management.create_group(groupID,member_id)
        print("密钥上传成功！")
    except:
        print(f"DID到p2p创建群聊失败")
        return 0

#8.群消息加密（已测试）
def group_meg_encrypt(groupID,did,data):
    try:
        group_key=En_Decrypt_Management.get_groupkey(groupID,did)
        encrypt_meg=En_Decrypt_Management.encrypt_by_sharekey(group_key,json.dumps(data).encode('utf-8'))
        return encrypt_meg        # 返回加密后的信息
    except:
        print(f"DID到p2p群消息加密失败")
        return 0

#9.群消息解密（已测试）
def group_meg_decrypt(groupID,did,encrypt_data):
    try:
        group_key=En_Decrypt_Management.get_groupkey(groupID,did)
        print(f"groupkey:{group_key}")
        decrypt_meg=En_Decrypt_Management.decrypt_by_sharekey(group_key,encrypt_data)
        return json.loads(decrypt_meg.decode('utf-8'))   # 返回解密后的信息
    except:
        print(f"DID到p2p群消息解密失败")
        return 0



# 本机从数据库读群聊基础信息，加载群聊信息时也可调用
def get_all_groups(owner):
    cursor.execute("SELECT groupId, groupname,members,timestamp,owner from tblGroup where owner = ?",
                   (owner,))  # members这个字段包括了群成员的基本信息，以及在线状态

    rows = cursor.fetchall()  # 取出所有的群成员（包括群主）信息

    # 构建成列表字典格式（便于 JSON 序列化）
    groups = []
    for row in rows:
        group = {
            "groupId": row[0],
            "groupname": row[1],
            "members": row[2],
            "timestamp": row[3],
            "owner": row[4]
        }
        groups.append(group)

    conn.close()
    return groups



# 本机从数据库读取单人和群聊聊天记录
def get_all_messages(owner):
    with sqlite3.connect("p2p.db", check_same_thread=False) as conn:
        cursor = conn.cursor()
    # 获取设备信息
    cpu_id, disk_id, product_id = auth.get_device_info()

    # 获取单聊记录
    cursor.execute("SELECT id, friend_id, sent,message, timestamp ,is_sent ,owner FROM messages where owner = ?",
                   (owner,))
    private_rows = cursor.fetchall()
    private_msgs = []
    for row in private_rows:
        message = decrypt(cpu_id, disk_id, product_id, row["message"])  # 解密这条消息
        private_msgs.append({
            "id": row[0],
            "friend_id": row[1],
            "sent": row[2],
            "message": message,
            "timestamp": row[4],
            "is_sent": row[5],
            "owner": owner
        })

    # 获取群聊记录
    cursor.execute(
        "SELECT sender,receiver, message, timestamp,msg_type, groupId,owner FROM group_message where owner = ?",
        (owner,))
    group_rows = cursor.fetchall()
    group_msgs = []
    for group_row in group_rows:
        group_message = decrypt(cpu_id, disk_id, product_id, group_row["message"])  # 解密这条消息
        group_msgs.append({
            "sender": group_row[0],
            "receiver": group_row[1],
            "message": group_message,
            "timestamp": group_row[3],
            "msg_type": group_row[4],
            "groupId": group_row[5],
            "owner": owner
        })

    conn.close()
    # 打包成统一结构
    messages = {
        "private": private_msgs,
        "group": group_msgs
    }

    return messages


#    ------------------------部分函数-------------------------------

# 信息同步（本机）   sender_did:本机底层DID
def meg_sync(sender_did):
    try:
        listen_port = 8888
        if DID_listen(sender_did,listen_port):
            print("等待接收数据...")
        request=DID_recv()


        receiver_did=request.get("kuaji_did")
        if request.get("action")=="SYNC_REQUEST":
            modules=request.get("moudules",[])
            data=get_info(modules,sender_did)        # 导入


            # print(meg)
            encrypt_data = En_Decrypt_Management.encrypt_package(sender_did, receiver_did, json.dumps(data).encode('utf-8'))
            # print(f"encrypt:{encrypt_data}")
            serializable = {k: base64.b64encode(v).decode('ascii') for k, v in encrypt_data.items()}


            # print(f"ddd:{payload}")
            print("准备发送加密包")

            if DID_send(serializable):
                print("数据发送成功")
            response = DID_recv()
            print(f"收到响应：{response}")
            DID_close()
            return True

    except Exception as e:
        print(f"DID到p2p meg_sync失败:{e}")
        return 0








# 本机接收并同步跨机的信息
# 跨机   sender_did: 跨机底层did    receiver_did:本机底层did
def meg_sync_send(sender_did,receiver_did,data,ip):
    try:
        port=8888
        encrypt_data=En_Decrypt_Management.encrypt_package(sender_did,receiver_did,json.dumps(data).encode('utf-8'))
        # print(f"encrypt:{encrypt_data}")
        serializable = {k: base64.b64encode(v).decode('ascii') for k, v in encrypt_data.items()}

        payload = json.dumps(serializable).encode('utf-8')
        if Communication_Management.DID_connect(receiver_did,port,sender_did,ip):
            print("准备发送加密包")
            # print(f"ddd:{payload}")
        if Communication_Management.DID_send(payload):
            print("数据发送成功")
        response=Communication_Management.DID_recv()
        print(f"收到响应：{response.decode('utf-8')}")
        Communication_Management.DID_close()
        return 1
    except Exception as e:
        print(f"DID到p2p meg_sync_send失败:{e}")
        Communication_Management.DID_close()
        return 0

# 本机   receiver_did: 本机底层did
def meg_sync_receive(receiver_did):
    try:
        listen_port=8888
        if Communication_Management.DID_listen(receiver_did,listen_port):
            print("等待接收数据...")
        receive_data=json.loads(Communication_Management.DID_recv().decode('utf-8'))

        data = {k: base64.b64decode(v)  #  base64 字符串 -> 原始 bytes
                        for k, v in receive_data.items()}
        decrypt_data=En_Decrypt_Management.decrypt_package(data)


        print(f"收到同步信息")
        response="已收到同步信息"
        if Communication_Management.DID_send(response):
            print("响应发送成功")
        Communication_Management.DID_close()
        return decrypt_data
    except Exception as e:
        print(f"DID到p2p meg_sync_receive失败:{e}")
        Communication_Management.DID_close()
        return 0

#7.创建群聊（准备密码包）(已测试)
def create_and_share_groupkey(groupID,member_id):
    try:                                   # 为方便遍历，群成员id(即DID)请用数组(即列表)打包，其中第一个元素为群主DID
        En_Decrypt_Management.create_group(groupID,member_id)
        print("密钥上传成功！")
    except:
        print(f"DID到p2p创建群聊失败")
        return 0

#8.群消息加密（已测试）
def group_meg_encrypt(groupID,did,data):
    try:
        group_key=En_Decrypt_Management.get_groupkey(groupID,did)
        encrypt_meg=En_Decrypt_Management.encrypt_by_sharekey(group_key,json.dumps(data).encode('utf-8'))
        return encrypt_meg        # 返回加密后的信息
    except:
        print(f"DID到p2p群消息加密失败")
        return 0

#9.群消息解密（已测试）
def group_meg_decrypt(groupID,did,encrypt_data):
    try:
        group_key=En_Decrypt_Management.get_groupkey(groupID,did)
        print(f"groupkey:{group_key}")
        decrypt_meg=En_Decrypt_Management.decrypt_by_sharekey(group_key,encrypt_data)
        return json.loads(decrypt_meg.decode('utf-8'))   # 返回解密后的信息
    except:
        print(f"DID到p2p群消息解密失败")
        return 0
